from django.db import models
from users.models import CustomUser
from products.models import Product
from users.models import Address
from django.core.validators import MaxLengthValidator  # 新增导入
from django.utils import timezone
from datetime import timedelta  # Add this import
import uuid
import time
def generate_order_code():
    # 生成18位数字（时间戳14位+随机数4位）
    timestamp = time.strftime("%Y%m%d%H%M%S")
    random_part = str(uuid.uuid4().int)[:4]
    return f"{timestamp}{random_part}"

def payment_expire_default():
    return timezone.now() + timedelta(minutes=30)

class Order(models.Model):
    STATUS_CHOICES = (
        (0, '待支付'),
        (1, '待发货'),
        (2, '待收货'),
        (3, '已完成'),
        (4, '已取消')
    )

    order_code = models.CharField(
        max_length=24,  # 从20增加到24字符
        unique=True,
        verbose_name='订单编号',
        editable=False,
        default=generate_order_code  # 添加自动生成函数
    )

    buyer = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='buyer_orders',db_index=False)
    seller = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='seller_orders',db_index=False)
    product = models.ForeignKey(Product, on_delete=models.CASCADE,db_index=False,verbose_name='商品')
    tracking_number = models.CharField(max_length=50, blank=True, null=True,verbose_name='快递单号')
    quantity = models.PositiveIntegerField(default=1)
    snapshot_price = models.DecimalField(max_digits=10, decimal_places=2,verbose_name='快照价格')
    address = models.ForeignKey(Address, on_delete=models.CASCADE,verbose_name='收货地址')
    status = models.SmallIntegerField(choices=STATUS_CHOICES)
    create_time = models.DateTimeField(auto_now_add=True)
    payment_time = models.DateTimeField(blank=True, null=True)
    payment_status = models.CharField(
        max_length=20,
        choices=[
            ('pending', '待支付'),
            ('paid', '已支付'),
            ('expired', '已超时')
        ],
        default='pending',
        verbose_name='支付状态'
    )

    # 新增支付超时时间（自动计算）
    payment_expire_time = models.DateTimeField(
        verbose_name="支付超时时间",
        default=payment_expire_default
    )
    deliver_time = models.DateTimeField(
        blank=True,
        null=True, 
        verbose_name='发货时间'
    )
    complete_time = models.DateTimeField(
        blank=True,
        null=True,
        verbose_name='完成时间'
    )
    pickup_location = models.CharField(max_length=100, blank=True, null=True)  # 新增


    class Meta:
        db_table = 'ORDERS'
        ordering = ['-create_time']
        indexes = [
            models.Index(fields=['buyer', 'status'], name='idx_buyer_status', db_tablespace='SECONDTRADE'),
            models.Index(fields=['seller', 'status'], name='idx_seller_status',db_tablespace='SECONDTRADE'),
            models.Index(fields=['create_time'], name='idx_create_time',db_tablespace='SECONDTRADE'),
        ]

class OrderLog(models.Model):
    ACTION_CHOICES = (
        ('create', '创建订单'),
        ('pay', '支付订单'),
        ('ship', '发货'),
        ('confirm', '确认收货'),
        ('cancel', '取消订单')
    )
    
    order = models.ForeignKey(Order,on_delete=models.CASCADE, related_name='logs',verbose_name='关联订单')
    action = models.CharField(
        max_length=20,
        choices=ACTION_CHOICES,
        verbose_name='操作类型'
    )
    operator = models.ForeignKey(
        CustomUser,
        on_delete=models.PROTECT,
        verbose_name='操作人'
    )
    detail = models.TextField(
        blank=True,
        null=True,
        verbose_name='操作详情'
    )
    ip_address = models.GenericIPAddressField(
        blank=True,
        null=True,
        verbose_name='操作IP'
    )
    created_at = models.DateTimeField(auto_now_add=True,verbose_name='操作创建时间')

    class Meta:
        db_table = 'ORDER_LOGS'
        verbose_name = '订单日志'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']
        # 达梦数据库特定配置
        default_permissions = ()
        managed = True
        indexes = [
            models.Index(fields=['order', 'action'], name='idx_order_action'),
        ]

class Reviews(models.Model):
    RATING_CHOICES = (
        (1, '⭐'),
        (2, '⭐⭐'),
        (3, '⭐⭐⭐'),
        (4, '⭐⭐⭐⭐'),
        (5, '⭐⭐⭐⭐⭐')
    )
    
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='reviews')
    buyer = models.ForeignKey(CustomUser, on_delete=models.CASCADE,verbose_name='评论人')
    content = models.TextField(verbose_name='评论内容',validators=[MaxLengthValidator(500)])
    rating = models.SmallIntegerField(choices=RATING_CHOICES)
    review_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'REVIEWS'
        verbose_name = '买家评价表'
        verbose_name_plural = verbose_name
        ordering = ['-review_time']
        # 达梦数据库特定配置
        default_permissions = ()
        managed = True
        constraints = [
            models.UniqueConstraint(
                fields=['order', 'buyer'],
                name='unique_order_buyer_review'
            )
        ]